<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <el-row v-if="$route.query.oppoId">
            <el-col :span="24">
              <el-form-item label="合同情况">
                <el-radio-group v-model="situation">
                  <el-radio :label="1">新建合同</el-radio>
                  <el-radio :label="2">关联已有合同</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="situation==1">
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input class="input-item" v-model="ruleForm.contractName" placeholder="请输入" maxlength="20"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractCode">
                  <el-input class="input-item" v-model="ruleForm.contractCode" placeholder="请输入" maxlength="20"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位名称" prop="customerId">
                  <el-select v-model="ruleForm.customerId" filterable placeholder="请选择">
                    <el-option v-for="(item,index) in customerlist" :key="index"
                      :label="item.custName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业联系人" prop="contactPerson">
                  <el-input class="input-item" v-model="ruleForm.contactPerson" placeholder="请输入" maxlength="8"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="telephone">
                  <el-input class="input-item" v-model="ruleForm.telephone" placeholder="请输入" maxlength="11" type='tel' onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责人" prop="directorUserId">
                  <el-select v-model="ruleForm.directorUserId" filterable placeholder="请选择">
                    <el-option v-for="item in listUsers" :key="item.userId"
                    :label="item.showName" :value="item.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款方式" prop="paymentMethod">
                  <el-select v-model="ruleForm.paymentMethod" placeholder="请选择">
                    <el-option label="一次付清" :value="1"></el-option>
                    <el-option label="两次付清" :value="2"></el-option>
                    <el-option label="三次付清" :value="3"></el-option>
                    <el-option label="四次付清" :value="4"></el-option>
                    <el-option label="五次付清" :value="5"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签约时间" prop="signingDate">
                  <el-date-picker v-model="ruleForm.signingDate" type="date" placeholder="选择日期"
                  format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="到期时间" prop="finishDate">
                  <el-date-picker v-model="ruleForm.finishDate" type="date" placeholder="选择日期"
                  format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务类型" prop="businessType">
                  <el-cascader v-model="ruleForm.businessType"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="false"
                    clearable
                    @change="businessChange"></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="businessCode=='ZB'">
                <el-form-item label="签约标段" prop="stageNumber">
                  <el-select v-model="ruleForm.stageNumber" multiple collapse-tags placeholder="请选择" @change="selectStageNumber">
                    <el-option label="标段一" :value="1"></el-option>
                    <el-option label="标段二" :value="2"></el-option>
                    <el-option label="标段三" :value="3"></el-option>
                    <el-option label="标段四" :value="4"></el-option>
                    <el-option label="标段五" :value="5"></el-option>
                    <el-option label="标段六" :value="6"></el-option>
                    <el-option label="标段七" :value="7"></el-option>
                    <el-option label="标段八" :value="8"></el-option>
                    <el-option label="标段九" :value="9"></el-option>
                    <el-option label="标段十" :value="10"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额(元)" :prop="businessCode=='ZB'?'':'contractAmount'">
                  <el-input type="number" class="input-item"
                  v-model="ruleForm.contractAmount"
                  placeholder="请输入" maxlength="20"
                  oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}" :disabled="businessCode=='ZB'?true:false"></el-input>
                </el-form-item>
                <el-table ref="table" :data="ruleForm.contractStageDtos" size="mini" header-cell-class-name="table-header-gray" v-if="businessCode=='ZB'">
                  <el-table-column prop="stageNumber" align="center" label="标段">
                    <template slot-scope="scope">标段{{scope.row.stageNumber}}</template>
                  </el-table-column>
                  <el-table-column prop="createTime" align="center" label="分项合同金额(元)">
                    <template slot="header">
                      <span>分项合同金额(元)<span style="color:red;font-size:16px;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                      <el-form-item class="table_input" :prop="'contractStageDtos.' + scope.$index + '.stageAmount'" :rules="rules.stageAmount">
                        <el-input type="number" class="input-item"
                        v-model="scope.row.stageAmount"
                        placeholder="请输入" maxlength="20"
                        oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}" @input="getstageAmount()"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属项目">
                  <el-select v-model="ruleForm.projectId" placeholder="请选择" v-if="businessCode!='ZB'" @change="selectproject">
                    <el-option v-for="(item,index) in projectlist" :key="index"
                    :label="item.projectName" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-table ref="table" :data="ruleForm.contractStageDtos" size="mini" style="margin-bottom: 20px;" header-cell-class-name="table-header-gray" v-if="businessCode=='ZB'">
                  <el-table-column prop="stageNumber" align="center" label="标段">
                    <template slot-scope="scope">标段{{scope.row.stageNumber}}</template>
                  </el-table-column>
                  <el-table-column prop="projectId" align="center" label="分项所属项目">
                    <template slot-scope="scope">
                      <el-form-item class="table_input">
                        <el-select v-model="scope.row.projectId" placeholder="请选择" @change="selectprojectOne()">
                          <el-option v-for="(item,index) in projectlist" :key="index"
                          :label="item.projectName" :value="item.id"></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目属性" prop="projectAttribute">
                  <el-select v-model="ruleForm.projectAttribute" placeholder="请选择">
                    <el-option label="公司项目" :value="1"></el-option>
                    <el-option label="合作单位" :value="2" v-if="(cooperateFlag==1&&stageFlag==0)||(cooperateFlag==1&&stageFlag==1)"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合作单位" prop="cooperateCompany" v-if="ruleForm.projectAttribute==2&&cooperateFlag==1&&stageFlag==1">
                  <el-select v-model="ruleForm.cooperateCompany" placeholder="请选择">
                    <el-option label="物产公司" :value="1"></el-option>
                    <el-option label="刘玲群" :value="2"></el-option>
                    <el-option label="其他单位" :value="3"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input class="input-item" v-model="ruleForm.remarks" placeholder="请输入"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="24">
              <el-form-item label="合同附件" prop="fileIds">
                <el-upload class="upload-demo"
                  :action="action"
                  :on-change="handleSuccess"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :accept="acceptStr"
                  multiple
                  :file-list="fileLists">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/word/pdf/ppt文件，且不超过500MB</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else>
            <el-col :span="12">
              <el-form-item label="选择合同" prop="contractId">
                <el-select v-model="ruleForm.contractId" filterable placeholder="请选择">
                  <el-option v-for="(item,index) in contractlist" :key="index"
                    :label="item.contractName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button @click="resetForm">取消</el-button>
              <el-button type="primary" @click="submitForm()">确定</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Customers, BusinessOpportunities } from '@/api/commercial.js';
import { Businesstype } from '@/api/business.js';
import { Contracts, Administration, fileUploadFileDo } from '@/api/projectAdministration.js';
export default {
  name: 'Winasingle',
  props: {
    contractId: {
      default: undefined
    }
  },
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入'))
      } else {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      loading: false,
      isShowloading: false,
      action: fileUploadFileDo,
      fileLists: [],
      acceptStr: '.doc,.docx,.xls,.xlsx,.jpg,.png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      tableData: [],
      tableData2: [],
      businessCode: '',
      stageFlag: '',
      cooperateFlag: '',
      businesstypeTree: [],
      businessType: '',
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      listUsers: [],
      customerlist: [],
      contractlist: [],
      projectlist: [],
      situation: 1,
      ruleForm: {
        contractId: '',
        contractName: '',
        contractCode: '',
        customerId: '',
        contactPerson: '',
        telephone: '',
        directorUserId: '',
        paymentMethod: '',
        signingDate: '',
        finishDate: '',
        businessType: '',
        contractAmount: '',
        stageNumber: '',
        contractStageDtos: [],
        projectAttribute: '',
        projectId: '',
        cooperateCompany: '',
        fileIds: '',
        remarks: ''
      },
      rules: {
        contractName: [{ required: true, message: '请输入', trigger: 'blur' }],
        contractCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        customerId: [{ required: true, message: '请选择', trigger: 'change' }],
        contactPerson: [{ required: true, message: '请输入', trigger: 'blur' }],
        telephone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        directorUserId: [{ required: true, message: '请选择', trigger: 'blur' }],
        paymentMethod: [{ required: true, message: '请输入', trigger: 'blur' }],
        signingDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        finishDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择', trigger: 'change' }],
        stageNumber: [{ required: true, message: '请选择', trigger: 'change' }],
        contractAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        projectAttribute: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        cooperateCompany: [{ required: true, message: '请选择', trigger: 'change' }],
        fileIds: [{ required: true, message: '请上传', trigger: 'blur' }],
        contractId: [{ required: true, message: '请选择', trigger: 'change' }],
        stageAmount: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  created () {
  },
  computed: {
  },
  mounted () {
    this.loadbusinesstypeTree()
    this.listGroupUser()
    this.loadCustomerList()
    if (this.$route.query.contractId) {
      this.loadContractdetail()
    }
    if (this.$route.query.oppoId) {
      this.loadOpportunitiesdetail()
    }
  },
  methods: {
    /**
     * 合同详情
     */
    loadContractdetail () {
      let params = {
        id: this.$route.query.contractId
      }
      return new Promise((resolve, reject) => {
        Contracts.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.stageFlag = res.data.stageFlag
          this.cooperateFlag = res.data.cooperateFlag
          this.businessCode = res.data.businessCode
          this.ruleForm.stageNumber = []
          let contractStageVoList = res.data.contractStageVoList
          if (contractStageVoList) {
            contractStageVoList.forEach(item => {
              this.ruleForm.stageNumber.push(item.stageNumber)
            })
            this.ruleForm.contractStageDtos = contractStageVoList
          }
          this.ruleForm.fileIds = []
          let file = res.data.contractFileVoList
          if (file.length !== 0) {
            file.forEach((item) => {
              this.ruleForm.fileIds.push(item.filePath)
            })
            this.fileLists = file.map(items => {
              return {
                name: items.fileName,
                response: {
                  data: items
                }
              }
            })
          }
          this.loadProjectList()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 商机详情
     */
    loadOpportunitiesdetail () {
      let params = this.$route.query.oppoId
      return new Promise((resolve, reject) => {
        BusinessOpportunities.detail(this, params).then(res => {
          this.businessType = res.data.businessType
          this.loadContractlist()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange () {
      this.businessCode = ''
      this.ruleForm.projectAttribute = ''
      this.stageFlag = ''
      this.cooperateFlag = ''
      let checkedNodes = this.$refs['ref_business'].getCheckedNodes()
      this.businessCode = checkedNodes[0].data.businessCode
      this.stageFlag = checkedNodes[0].data.stageFlag
      this.cooperateFlag = checkedNodes[0].data.cooperateFlag
      this.loadProjectList()
      this.$refs['ref_business'].dropDownVisible = false
    },
    /**
     * 合同列表
     */
    loadContractlist () {
      let params = {
        businessType: this.businessType
      }
      return new Promise((resolve, reject) => {
        Contracts.lists(this, params).then(res => {
          this.contractlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目列表
     */
    loadProjectList () {
      let params = {
        businessType: this.ruleForm.businessType
      }
      return new Promise((resolve, reject) => {
        Administration.listFor(this, params).then(res => {
          this.projectlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目选择
     */
    selectproject (data) {
      this.projectlist.forEach(item => {
        if (item.id === data) {
          this.ruleForm.contractCode = item.projectCode
        }
      })
    },
    /**
     * 标段项目选择
     */
    selectprojectOne (data) {
      this.ruleForm.contractStageDtos.forEach(item => {
        this.projectlist.forEach(items => {
          if (item.id === items.id) {
            this.ruleForm.contractCode = item.projectCode
            return false
          }
        })
      })
    },
    /**
     * 客户列表
     */
    loadCustomerList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.lists(this, params).then(res => {
          this.customerlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 人员列表
     */
    listGroupUser () {
      return new Promise((resolve, reject) => {
        Contracts.listForOppoAndContract(this).then(res => {
          this.listUsers = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    // 签约标段
    selectStageNumber (data) {
      let lenght = data.length
      let lenght1 = this.ruleForm.contractStageDtos.length
      if (lenght > lenght1) {
        data.forEach(item => {
          let info = this.ruleForm.contractStageDtos.find(items => {
            return item === items.stageNumber
          })
          if (!info) {
            let Obj = {
              projectId: '',
              stageAmount: '',
              stageNumber: item
            }
            this.ruleForm.contractStageDtos.push(Obj)
          }
        })
      } else {
        this.ruleForm.contractStageDtos.forEach((item, index) => {
          let info = data.find(items => {
            return items === item.stageNumber
          })
          if (!info) {
            this.ruleForm.contractStageDtos.splice(index, 1)
          }
        })
      }
      this.$forceUpdate()
    },
    // 标段总金额（元）
    getstageAmount () {
      let contractStageDtos = this.ruleForm.contractStageDtos
      let stageAmount = 0
      contractStageDtos.forEach(item => {
        stageAmount = Number(stageAmount) + Number(item.stageAmount)
      })
      this.ruleForm.contractAmount = stageAmount;
    },
    /**
     * 上传文件-成功
     */
    handleSuccess (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传文件-删除
     */
    handleRemove (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传图片限制条件
     */
    beforeAvatarUpload (file, fileList) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt200K = file.size / 1024 < 200
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      //   return false
      // }
      // if (!isLt200K) {
      //   this.$message.error('上传头像图片大小不能超过 200KB!')
      //   return false
      // }
      // return isJPG && isLt200K
    },
    /**
     * 提交表单
     */
    submitForm () {
      if (this.fileLists.length !== 0) {
        let filesnew = []
        this.fileLists.forEach((item) => {
          filesnew.push(item.response.data.fileId)
        })
        this.ruleForm.fileIds = filesnew
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          if (this.$route.query.oppoId) { // 添加-商机新建合同
            this.ruleForm.businessOpportunityId = this.$route.query.oppoId
            if (this.ruleForm.contractId) { // 商机关联已有合同
              let params = {
                oppoToExistContractDto: {
                  businessOpportunityId: this.ruleForm.businessOpportunityId,
                  contractId: this.ruleForm.contractId
                }
              };
              return new Promise((resolve, reject) => {
                Contracts.oppoToExistContract(this, params).then(res => {
                  this.$message({
                    showClose: true,
                    message: '操作成功！',
                    type: 'success'
                  });
                  this.resetForm();
                }).catch(e => {
                  reject(e);
                });
              });
            } else { // 商机新建合同
              let params = {
                oppoToContractDto: this.ruleForm
              };
              return new Promise((resolve, reject) => {
                Contracts.oppoToContract(this, params).then(res => {
                  this.$message({
                    showClose: true,
                    message: '操作成功！',
                    type: 'success'
                  });
                  this.resetForm();
                }).catch(e => {
                  reject(e);
                });
              });
            }
          } else if (this.$route.query.contractId) { // 编辑合同
            let params = {
              updateDto: this.ruleForm
            };
            return new Promise((resolve, reject) => {
              Contracts.update(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                if (this.$route.query.verifyStatus) {
                  this.onCancel(true);
                } else {
                  this.$router.go(-1)
                }
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加-新建合同
            let params = {
              addDto: this.ruleForm
            };
            return new Promise((resolve, reject) => {
              Contracts.add(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                this.resetForm();
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm () {
      if (this.$route.query.verifyStatus) {
        this.onCancel(false);
      } else {
        this.$router.go(-1)
      }
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h4{margin-bottom: 0;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
.table_input /deep/.el-form-item__content{margin-left: 0 !important;}
.table_input.el-form-item{margin: 12px 0;}
/deep/.el-table{margin: 0 0 0 10px;width: calc(100% - 10px);}
/deep/.el-upload-list{width: 40%;}
</style>
